package com.heima.search.listener;

import com.heima.common.util.JsonUtils;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.search.service.impl.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;

import static com.heima.common.constants.message.Article2EsConstants.ARTICLE_2_ES_TOPIC;

@Component
@Slf4j
public class ArticlePubListener {
    @Autowired
    private ArticleSearchService articleSearchService;
    @KafkaListener(topics = ARTICLE_2_ES_TOPIC)
    public void receiveMsg(ConsumerRecord<String,String> record){
        Optional<ConsumerRecord<String, String>> optional = Optional.ofNullable(record);
        if (optional.isPresent()) {
            String value = record.value();
            log.info("search服务接受到的admin消息，value={}",value);
            if (StringUtils.isNotBlank(value)){
                ArticleDto articleDto = JsonUtils.toBean(value, ArticleDto.class);
                articleSearchService.importEs(Arrays.asList(articleDto));
            }
        }
    }

}
